package com.itbird.eventbus.core;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * 主线程执行器
 * Created by itbird on 2022/9/20
 */
public class HandlerPoster<T> extends Handler implements Poster<T> {
    final EventBus eventBus;
    ArrayBlockingQueue pendingPostQueue = new ArrayBlockingQueue(100);

    public HandlerPoster(EventBus eventBus, Looper looper) {
        super(looper);
        this.eventBus = eventBus;
    }

    @Override
    public void enqueue(SubscribeMethod subscription, T event) {
        //享元设计模式，缓存复用
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            pendingPostQueue.offer(pendingPost);
            sendMessage(obtainMessage());
        }
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        while (true) {
            PendingPost pendingPost = (PendingPost) pendingPostQueue.poll();
            if (pendingPost == null) {
                return;
            }

            eventBus.reflectCallSubscribeMethod(pendingPost.getEvent(), pendingPost.getSubscription());
            pendingPost.recycle();
        }
    }
}
